package com.cqjtu.checkbook;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    //listView
    private MyDBHelper dbHelper;
    private List<Student> studentList = new ArrayList<Student>();
    private List<Student> suiJi_stu_list = new ArrayList<Student>();
    private ViewPager mViewPager;
    private PagerAdapter mAdapter;
    private List<View> mViews = new ArrayList<>();

    private RadioGroup mRadioGroup;
    //资料卡中imageview
    private ImageView mDialog_img;
    //新增学生信息中的照片imageView
    private ImageView mPre_img;
    //TAB
    private LinearLayout mTabSuiji;
    private LinearLayout mTabAll;
    private LinearLayout mTabSetting;

    private ImageButton mSuijiImg;
    private ImageButton mAllImg;
    private ImageButton mSettingImg;

    private Button mSuiji_btn;
    private Button mContinue_btn;
    private TextView textView5;
    //当前被选中的学生
    private Student stu;

    private AlertDialog mDialog;
    //全部名单
    private  ListView listView01;
    //随机名单
    private ListView listView02;
    private static int suijirenshu = 10;
    private LinearLayout tab01_top;
    private LinearLayout tab01_listView;
    private ImageButton btnRegister;
    private Button mComplateBtn;
    private Button mJilubanBtn;
    //private Bitmap pre_camare ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initDB();
        initView();
        /**tab02
         * 详细页面start
         */
        initStudent();

        final StudentAdapter adapter = new StudentAdapter(MainActivity.this,R.layout.stu_item,studentList);
        listView01 = (ListView) mViews.get(1).findViewById(R.id.list_view);

        listView01.setAdapter(adapter);
        listView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {

                //这里就是创建一个弹出的对话框
                stu  = (Student) listView01.getItemAtPosition(i);
                textView5 = (TextView) view.findViewById(R.id.text5);
                LayoutInflater mInflater = LayoutInflater.from(MainActivity.this);
                View dia_view = mInflater.inflate(R.layout.dialog_layout,null);
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                TextView zaiqin = (TextView) dia_view.findViewById(R.id.id_zaiqin);
                TextView chidao = (TextView) dia_view.findViewById(R.id.id_chidao);
                TextView zaotui = (TextView) dia_view.findViewById(R.id.id_zaotui);
                TextView kuangke = (TextView) dia_view.findViewById(R.id.id_kuangke);
                TextView bingjia = (TextView) dia_view.findViewById(R.id.id_bingjia);
                mDialog_img = (ImageView) dia_view.findViewById(R.id.dialog_img);
                mDialog_img.setImageBitmap(stu.getBitmap());
                zaiqin.setText(stu.getZaiqin()+"");
                chidao.setText(stu.getChidao()+"");
                zaotui.setText(stu.getZaotui()+"");
                kuangke.setText(stu.getKuangke()+"");
                bingjia.setText(stu.getBingjia()+"");
                mBuilder.setCancelable(false);
                mDialog_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                        intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                        startActivityForResult(intent, 1);
                    }
                });
                mRadioGroup = (RadioGroup) dia_view.findViewById(R.id.id_dia_group);
                mRadioGroup.check(R.id.dia_one);
                mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        Log.i("onCheckedChanged", "onCheckedChanged: "+i);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        switch (i){

                            case R.id.dia_two:
                                stu.setState("迟到");
                                textView5.setText("迟到");
                                textView5.setTextSize(21);
                                textView5.setTextColor(Color.YELLOW);
                                stu.setChidao(stu.getChidao()+1);
                                values.put("chidao",stu.getChidao());
                                values.put("State","迟到");
                                db.update("CheckBook",values,"id=?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_three:
                                stu.setState("早退");
                                textView5.setText("早退");
                                textView5.setTextColor(Color.RED);
                                stu.setZaotui(stu.getZaotui()+1);
                                values.put("zaotui",stu.getZaotui());
                                values.put("State","早退");
                                db.update("CheckBook",values,"id=?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_four:
                                stu.setState("旷课");
                                textView5.setText("旷课");
                                textView5.setTextColor(Color.RED);
                                stu.setKuangke(stu.getKuangke()+1);
                                values.put("kuangke",stu.getKuangke());
                                values.put("State","旷课");
                                db.update("CheckBook",values,"id=?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_five:
                                stu.setState("病假");
                                textView5.setText("病假");
                                textView5.setTextColor(Color.GRAY);
                                stu.setBingjia(stu.getBingjia()+1);
                                values.put("bingjia",stu.getBingjia());
                                values.put("State","病假");
                                db.update("CheckBook",values,"id=?",new String[]{ stu.getId()+""});
                                break;

                        }

                    }
                });



                TextView dia_name = (TextView) dia_view.findViewById(R.id.dialog_name);
                dia_name.setText(stu.getSname());
                mBuilder.setTitle("学生信息");
                mBuilder.setView(dia_view);

                mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();
                    }
                });
                mBuilder.setNegativeButton("删除该学生", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int in) {
                        studentList.remove(i);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        db.delete("CheckBook","id = ?",new String[]{ stu.getId()+""  });
                        adapter.notifyDataSetChanged();
                    }
                });
                mDialog = mBuilder.create();
                mDialog.show();


            }
        });
        /**End
         * 详细页面end
         */

        btnRegister = (ImageButton) mViews.get(1).findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final boolean[] checkBaseInfo = {false};
                LayoutInflater mInflater = LayoutInflater.from(MainActivity.this);
                View dia_view = mInflater.inflate(R.layout.sturegister,null);
                final EditText pre_name = (EditText) dia_view.findViewById(R.id.id_name_pre);
                final EditText pre_xuehao = (EditText) dia_view.findViewById(R.id.id_xuehao_pre);
                final EditText pre_banji = (EditText) dia_view.findViewById(R.id.id_pre_banji);
                mPre_img = (ImageView) dia_view.findViewById(R.id.id_img_preview);
                Button pre_base_btn = (Button) dia_view.findViewById(R.id.id_pre_base_btn);



                pre_base_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        checkBaseInfo[0] = true;
                        String name = pre_name.getText().toString();
                        String xuehao = pre_xuehao.getText().toString();
                        String banji = pre_banji.getText().toString();
                        if(name!=null&&xuehao!=null&&banji!=null){
                            stu = new Student(studentList.size()+1,xuehao,name,banji,"在勤",null,0,0,0,0,0);
                        }
                        pre_name.setEnabled(false);
                        pre_xuehao.setEnabled(false);
                        pre_banji.setEnabled(false);
                    }
                });
                Button pre_file = (Button) dia_view.findViewById(R.id.id_pre_file);
                pre_file.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(checkBaseInfo[0]) {
                            Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                            intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                            startActivityForResult(intent, 2);
                        }else{
                            Toast.makeText(MainActivity.this,"请先确定基本信息！",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                Button pre_camare = (Button) dia_view.findViewById(R.id.id_pre_camera);
                pre_camare.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(checkBaseInfo[0]) {
                            String state = Environment.getExternalStorageState(); //拿到sdcard是否可用的状态码
                            if (state.equals(Environment.MEDIA_MOUNTED)) {   //如果可用
                                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                startActivityForResult(intent, 3);
                            }
                        }else{
                            Toast.makeText(MainActivity.this,"请先确定基本信息！",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       studentList.add(stu);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.put("id",stu.getId());
                        values.put("Sno",stu.getSno());
                        values.put("Sname",stu.getSname());
                        values.put("Sclass",stu.getBanji());
                        values.put("State",stu.getState());
                        values.put("zaiqin",stu.getZaiqin());
                        values.put("chidao",stu.getChidao());
                        values.put("zaotui",stu.getZaotui());
                        values.put("kuangke",stu.getKuangke());
                        values.put("bingjia",stu.getBingjia());
                        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        stu.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos);
                        values.put("img",baos.toByteArray());
                        db.insert("CheckBook",null,values);
                        adapter.notifyDataSetChanged();
                    }
                });
                mBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        stu = null;
                        mDialog.dismiss();
                    }
                });
                mBuilder.setTitle("增加学生");
                mBuilder.setView(dia_view);
                mBuilder.setCancelable(false);
                mDialog = mBuilder.create();
                mDialog.show();
            }
        });

    }



    private void initView() {
        //buttom初始化
        mViewPager = (ViewPager) findViewById(R.id.id_viewPager);
        mTabSuiji = (LinearLayout) findViewById(R.id.id_tab_suiji);
        mTabAll = (LinearLayout) findViewById(R.id.id_tab_all);
        mTabSetting = (LinearLayout) findViewById(R.id.id_tab_setting);
        //
        mSuijiImg = (ImageButton) findViewById(R.id.id_tab_suiji_img);
        mAllImg = (ImageButton) findViewById(R.id.id_tab_all_img);
        mSettingImg = (ImageButton) findViewById(R.id.id_tab_setting_img);

        LayoutInflater mInflater = LayoutInflater.from(this);
        View tab01 = mInflater.inflate(R.layout.tab01,null);
        View tab02 = mInflater.inflate(R.layout.tab02,null);
        View tab03 = mInflater.inflate(R.layout.tab03,null);
        mViews.add(tab01);
        mViews.add(tab02);
        mViews.add(tab03);


        //tab点击事件
        mTabSuiji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetImg();
                mSuijiImg.setImageResource(R.drawable.question);
                mViewPager.setCurrentItem(0);
            }
        });
        mAllImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetImg();
                mAllImg.setImageResource(R.drawable.tab_find_frd_pressed);
                mViewPager.setCurrentItem(1);
            }
        });
        mSettingImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetImg();
                mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
                mViewPager.setCurrentItem(2);
            }
        });



        //




        mAdapter = new PagerAdapter() {
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
              container.removeView(mViews.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = mViews.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public int getCount() {
                return mViews.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }
        };
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int currentItem = mViewPager.getCurrentItem();
                resetImg();
                switch (currentItem){
                    case 0:
                        mSuijiImg.setImageResource(R.drawable.question);
                        break;
                    case 1:
                        mAllImg.setImageResource(R.drawable.tab_find_frd_pressed);
                        break;
                    case 2:
                        mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        randomCheck();//随机点名方法
        settingRandom();//tab03中设置随机人数


    }

    private void resetImg() {
        mSuijiImg.setImageResource(R.drawable.question2);
        mAllImg.setImageResource(R.drawable.tab_find_frd_normal);
        mSettingImg.setImageResource(R.drawable.tab_settings_normal);
    }

    private void settingRandom() {
       Spinner tab03_spinner = (Spinner) mViews.get(2).findViewById(R.id.id_spinner_tab03);
        mComplateBtn = (Button) mViews.get(2).findViewById(R.id.id_btn_complate);
        tab03_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String[] renshu = getResources().getStringArray(R.array.renshu);
                suijirenshu = Integer.valueOf(renshu[i].substring(0,renshu[i].length()-1));
              //  Log.d("suijirenshu", "onItemSelected: "+suijirenshu);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        mComplateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                for(int k = 0; k < studentList.size(); k++)
                {
                    Student temp = studentList.get(k);
                    if(temp.getState().equals("在勤")){
                        temp.setZaiqin(temp.getZaiqin()+1);
                    }
                    values.put("zaiqin",stu.getZaiqin());
                    values.put("State","在勤");
                    db.update("CheckBook",values,"id=?",new String[]{ stu.getId()+""});
                    temp.setState("在勤");
                }
                suiJi_stu_list.removeAll(suiJi_stu_list);
                //studentList.removeAll(studentList);
//                values.put("State","在勤");
//                db.update("CheckBook", values,null,null);

                //initStudent();
                StudentAdapter adapter = new StudentAdapter(MainActivity.this,R.layout.stu_item,studentList);
                StudentAdapter adapter2 = new StudentAdapter(MainActivity.this,R.layout.stu_item,suiJi_stu_list);
                Toast.makeText(MainActivity.this,"成功记录数据！并初始化下次点名！",Toast.LENGTH_SHORT).show();
                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            }
        });

    }

    private void randomCheck() {
        /**
         * tab01 中的随机点名按钮初始化
         */

        mSuiji_btn = (Button) mViews.get(0).findViewById(R.id.id_suiji_btn);
        mContinue_btn = (Button)mViews.get(0).findViewById(R.id.id_continue_btn);
        tab01_top = (LinearLayout) mViews.get(0).findViewById(R.id.id_tab01_top);
        tab01_listView = (LinearLayout) mViews.get(0).findViewById(R.id.id_tab01_listView);
        mSuiji_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                suiJi_stu_list.removeAll(suiJi_stu_list);
                java.util.Random r=new java.util.Random();
                for(int i = 0;i<suijirenshu;i++){
                    initSuiJiList(r.nextInt(studentList.size()-1)+1);
                }
                mSuiji_btn.setVisibility(View.GONE);
                mContinue_btn.setVisibility(View.VISIBLE);
                tab01_top.setVisibility(View.VISIBLE);
                tab01_listView.setVisibility(View.VISIBLE);

            }
        });
        final StudentAdapter adapter02 = new StudentAdapter(MainActivity.this,R.layout.stu_item,suiJi_stu_list);
        listView02 = (ListView) mViews.get(0).findViewById(R.id.list_view);
        listView02.setAdapter(adapter02);
        mContinue_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                suiJi_stu_list.removeAll(suiJi_stu_list);
                java.util.Random r=new java.util.Random();
                for(int i = 0;i<suijirenshu;i++){
                    initSuiJiList(r.nextInt(studentList.size()-1)+1);
                }
                adapter02.notifyDataSetChanged();
            }
        });


        listView02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //这里就是创建一个弹出的对话框
                stu  = (Student) listView02.getItemAtPosition(i);
                textView5 = (TextView) view.findViewById(R.id.text5);
                LayoutInflater mInflater = LayoutInflater.from(MainActivity.this);
                View dia_view = mInflater.inflate(R.layout.dialog_layout,null);
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                mBuilder.setCancelable(false);
                mDialog_img = (ImageView) dia_view.findViewById(R.id.dialog_img);
                mDialog_img.setImageBitmap(stu.getBitmap());

                TextView zaiqin = (TextView) dia_view.findViewById(R.id.id_zaiqin);
                TextView chidao = (TextView) dia_view.findViewById(R.id.id_chidao);
                TextView zaotui = (TextView) dia_view.findViewById(R.id.id_zaotui);
                TextView kuangke = (TextView) dia_view.findViewById(R.id.id_kuangke);
                TextView bingjia = (TextView) dia_view.findViewById(R.id.id_bingjia);
                zaiqin.setText(stu.getZaiqin()+"");
                chidao.setText(stu.getChidao()+"");
                zaotui.setText(stu.getZaotui()+"");
                kuangke.setText(stu.getKuangke()+"");
                bingjia.setText(stu.getBingjia()+"");

                mRadioGroup = (RadioGroup) dia_view.findViewById(R.id.id_dia_group);
                mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                        Log.i("onCheckedChanged", "onCheckedChanged: "+i);
                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        switch (i){


                            case R.id.dia_two:
                                stu.setState("迟到");
                                textView5.setText("迟到");
                                textView5.setTextSize(21);
                                textView5.setTextColor(Color.YELLOW);
                                values.put("chidao",stu.getChidao()+1);
                                values.put("State","迟到");
                                db.update("CheckBook",values,"id = ?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_three:
                                stu.setState("早退");
                                textView5.setText("早退");
                                textView5.setTextColor(Color.RED);
                                values.put("zaotui",stu.getZaotui()+1);
                                values.put("State","早退");
                                db.update("CheckBook",values,"id = ?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_four:
                                stu.setState("旷课");
                                textView5.setText("旷课");
                                textView5.setTextColor(Color.RED);
                                values.put("kuangke",stu.getKuangke()+1);
                                values.put("State","旷课");
                                db.update("CheckBook",values,"id = ?",new String[]{ stu.getId()+""});
                                break;

                            case R.id.dia_five:
                                stu.setState("病假");
                                textView5.setText("病假");
                                textView5.setTextColor(Color.GRAY);
                                values.put("bingjia",stu.getBingjia()+1);
                                values.put("State","病假");
                                db.update("CheckBook",values,"id = ?",new String[]{ stu.getId()+""});
                                break;

                        }

                    }
                });

                TextView dia_name = (TextView) dia_view.findViewById(R.id.dialog_name);
                dia_name.setText(stu.getSname());
                mBuilder.setTitle("学生信息");
                mBuilder.setView(dia_view);

                mBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();
                    }
                });
                mDialog = mBuilder.create();
                mDialog.show();


            }
        });
    }

    private void initSuiJiList(int id) {
        if(!suiJi_stu_list.contains(studentList.get(id)))
        suiJi_stu_list.add(studentList.get(id));
    }

    private void initDB() {
        dbHelper = new MyDBHelper(this,"CheckBook.db",null,1);
        dbHelper.getWritableDatabase();
    }

    private void initStudent() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("CheckBook",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            do {
                byte[] in=cursor.getBlob(cursor.getColumnIndex("img"));
                Bitmap bitmap = BitmapFactory.decodeByteArray(in,0,in.length);
                Student stu = new Student(
                        cursor.getInt(cursor.getColumnIndex("id")),
                        cursor.getString(cursor.getColumnIndex("Sno")),
                        cursor.getString(cursor.getColumnIndex("Sname")),
                        cursor.getString(cursor.getColumnIndex("Sclass")),
                        cursor.getString(cursor.getColumnIndex("State")),
                        bitmap,
                        cursor.getInt(cursor.getColumnIndex("zaiqin")),
                        cursor.getInt(cursor.getColumnIndex("chidao")),
                        cursor.getInt(cursor.getColumnIndex("zaotui")),
                        cursor.getInt(cursor.getColumnIndex("kuangke")),
                        cursor.getInt(cursor.getColumnIndex("bingjia"))
                );
                studentList.add(stu);
                Log.i("initSuiJiList", "initSuiJiList: "+stu.getState());
            }while (cursor.moveToNext());
        }
        cursor.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1://修改学生照片
                if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                // Log.e("uri", uri.toString());
                ContentResolver cr = this.getContentResolver();
                //对图片进行压缩处理
                BitmapFactory.Options options = new  BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                // 默认是Bitmap.Config.ARGB_8888
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                try {
                    Bitmap mmbitmap = BitmapFactory.decodeStream(cr.openInputStream(uri),null,options);
                    int height = options.outHeight;
                    //压缩比例
                    int size = height/800;
                    if(size<=0){
                        size =2;
                    }
                /*inSampleSize表示缩略图大小为原始图片大小的几分之一，
                      即如果这个值为2，则取出的缩略图的宽和高都是原始图片的1/2，
                      图片大小就为原始大小的1/4*/
                    options.inSampleSize = size;
                    // 设置options.inJustDecodeBounds重新设置为false
                    options.inPurgeable = true;// 同时设置才会有效
                    options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
                    options.inJustDecodeBounds = false;
                    //此时图片会按比例压缩后被载入内存中
                    mmbitmap = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(uri), null, options);

                /* 将Bitmap设定到ImageView */
                    mDialog_img.setImageBitmap(mmbitmap);
                    stu.setBitmap(mmbitmap);
                    //更新数据库
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    mmbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    values.put("img",baos.toByteArray());
                    db.update("CheckBook",values,"id = ?",new String[]{ stu.getId()+""});
                } catch (FileNotFoundException e) {
                    Log.e("Exception", e.getMessage(),e);
                }
            }
                break;
            case 2://打开文件选取照片，类似case 1
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    // Log.e("uri", uri.toString());
                    ContentResolver cr = this.getContentResolver();
                    //对图片进行压缩处理
                    BitmapFactory.Options options = new  BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    // 默认是Bitmap.Config.ARGB_8888
                    options.inPreferredConfig = Bitmap.Config.RGB_565;


                    try {
                        Bitmap mmbitmap = BitmapFactory.decodeStream(cr.openInputStream(uri),null,options);
                        int height = options.outHeight;
                        //压缩比例
                        int size = height/800;
                        if(size<=0){
                            size =2;
                        }
                /*inSampleSize表示缩略图大小为原始图片大小的几分之一，
                      即如果这个值为2，则取出的缩略图的宽和高都是原始图片的1/2，
                      图片大小就为原始大小的1/4*/
                        options.inSampleSize = size;
                        // 设置options.inJustDecodeBounds重新设置为false
                        options.inPurgeable = true;// 同时设置才会有效
                        options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
                        options.inJustDecodeBounds = false;
                        //此时图片会按比例压缩后被载入内存中
                        mmbitmap = BitmapFactory.decodeStream(getContentResolver()
                                .openInputStream(uri), null, options);

                /* 将Bitmap设定到ImageView */
                        mPre_img.setImageBitmap(mmbitmap);
                        stu.setBitmap(mmbitmap);

                    } catch (FileNotFoundException e) {
                        Log.e("Exception", e.getMessage(),e);
                    }
                }
                break;
            case 3://照相选取照片
                if (resultCode == RESULT_OK) {
                    //对图片进行压缩处理
                    BitmapFactory.Options options = new  BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    // 默认是Bitmap.Config.ARGB_8888
                    options.inPreferredConfig = Bitmap.Config.RGB_565;

                     int height = options.outHeight;
                     //压缩比例
                     int size = height / 800;
                     if (size <= 0) {
                        size = 1/2;
                    }


                        options.inSampleSize = size;
                        // 设置options.inJustDecodeBounds重新设置为false
                        options.inPurgeable = true;// 同时设置才会有效
                        options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
                        options.inJustDecodeBounds = false;
                        //此时图片会按比例压缩后被载入内存中
                        Bitmap mmbitmap = null;
                        if (data.getData() != null || data.getExtras() != null) { //防止没有返回结果
                            Uri uri = data.getData();
                            if (uri != null) {
                                mmbitmap = BitmapFactory.decodeFile(uri.getPath(), options); //拿到图片

                            }
                            if (mmbitmap == null) {
                                Bundle bundle = data.getExtras();
                                if (bundle != null) {
                                    mmbitmap = (Bitmap) bundle.get("data");
                                }
                            }
                            mPre_img.setImageBitmap(mmbitmap);
                            stu.setBitmap(mmbitmap);
                            //更新数据库
                            SQLiteDatabase db = dbHelper.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            mmbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                            values.put("img", baos.toByteArray());
                            db.update("CheckBook", values, "id = ?", new String[]{stu.getId() + ""});
                    }
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


}
